import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/content.dart';

class ContentRepository {
  // 新增内容
  Future<int> addContent(Content content) async {
    final db = await DBHelper.database;
    return await db.insert('content', content.toMap());
  }

  // 创建内容并返回完整的Content对象
  Future<Content> createContent(Content content) async {
    final db = await DBHelper.database;
    final id = await db.insert('content', content.toMap());

    // 返回包含ID的Content对象
    return Content(
      id: id,
      picture: content.picture,
      description: content.description,
      userId: content.userId,
      topicId: content.topicId,
      publishedAt: content.publishedAt,
    );
  }

  // 获取所有内容
  Future<List<Content>> getAllContents() async {
    final db = await DBHelper.database;
    final res = await db.query('content', orderBy: 'publishedAt DESC');
    return res.map((e) => Content.fromMap(e)).toList();
  }

  // 按最新时间排序获取所有内容
  Future<List<Content>> getAllContentsByLatest() async {
    final db = await DBHelper.database;
    final res = await db.query('content', orderBy: 'publishedAt DESC');
    return res.map((e) => Content.fromMap(e)).toList();
  }

  // 按热度（评论数量）排序获取所有内容
  Future<List<Content>> getAllContentsByHot() async {
    final db = await DBHelper.database;
    final res = await db.rawQuery('''
      SELECT c.*, COUNT(r.id) as reviewCount
      FROM content c
      LEFT JOIN review r ON c.id = r.contentId
      GROUP BY c.id
      ORDER BY reviewCount DESC, c.publishedAt DESC
    ''');
    return res.map((e) => Content.fromMap(e)).toList();
  }

  // 根据用户ID获取内容
  Future<List<Content>> getContentsByUserId(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'content',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'id DESC',
    );
    return res.map((e) => Content.fromMap(e)).toList();
  }

  // 根据主题ID获取内容
  Future<List<Content>> getContentsByTopicId(int topicId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'content',
      where: 'topicId = ?',
      whereArgs: [topicId],
      orderBy: 'id DESC',
    );
    return res.map((e) => Content.fromMap(e)).toList();
  }

  // 获取主题的内容数量
  Future<int> getContentCountByTopicId(int topicId) async {
    final db = await DBHelper.database;
    final res = await db.rawQuery(
      'SELECT COUNT(*) as count FROM content WHERE topicId = ?',
      [topicId],
    );
    return res.first['count'] as int;
  }

  // 删除内容
  Future<int> deleteContent(int id) async {
    final db = await DBHelper.database;
    return await db.delete('content', where: 'id = ?', whereArgs: [id]);
  }

  // 更新内容
  Future<int> updateContent(Content content) async {
    final db = await DBHelper.database;
    return await db.update('content', content.toMap(), where: 'id = ?', whereArgs: [content.id]);
  }
}
